/**
 * Copyright (c) 2011-2016, Eason Pan(pylxyhome@vip.qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcbase.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.pojo.Lable;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.util.JqGridModelUtils;
import com.jcbase.core.util.StringUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.model.SysRole;
import com.jcbase.model.SysSite;
import com.jcbase.model.SysUser;
import com.jcbase.model.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 系统用户管理.
 * 
 * @author eason
 */

public class UserController extends JCBaseController
{

	@RequiresPermissions(value = { "/sys/user" })
	public void index()
	{
		render("user_index.jsp");
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void getListData()
	{
		String keyword = this.getPara("name");
		HashMap<Integer, String> siteMap = new HashMap<Integer, String>();
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		List<SysUserRole> list = SysRole.me.getRole(getRequest());
		Page<SysUser> pageInfo;
		if (SysRole.me.checkIsAdmin(list))
		{
			pageInfo = SysUser.me.getSysUserPage(this.getPage(), this.getRows(), keyword, this.getOrderbyStr());
		}
		else
		{
			StringBuilder selectSql = new StringBuilder();
			StringBuilder sqlExceptSelect = new StringBuilder();
			selectSql.append(
					"select su.*, (select group_concat(name) as roleNames from sys_role where id in(select role_id from sys_user_role where user_id=su.id)) as roleNames");
			sqlExceptSelect.append("from sys_user su ");
			sqlExceptSelect.append("where create_user_id = ");
			sqlExceptSelect.append(user.getId());
			pageInfo = SysUser.me.getPage(this.getPage(), this.getRows(), selectSql.toString(),
					sqlExceptSelect.toString(), this.getOrderby());

		}
		// 获取所有的站点信息
		List<SysSite> sysSiteList = SysSite.me.find("select * from sys_site");

		for (SysSite sysSite : sysSiteList)
		{
			siteMap.put(sysSite.getId(), sysSite.getName());
		}

		List<SysUser> UserList = pageInfo.getList();
		for (SysUser sysUser : UserList)
		{
			String siteId = sysUser.getSiteId();
			String siteName = "";
			if (!StringUtils.isBlank(siteId))
			{
				String[] site = siteId.split(",");
				for (String string : site)
				{
					String name = siteMap.get(Integer.parseInt(string));
					if (!StringUtils.isBlank(name))
					{
						siteName = siteName + name + ",";
					}
					else
					{
						continue;
					}
				}
				if (!StringUtils.isBlank(siteId))
				{
					siteName = siteName.substring(0, siteName.length() - 1);
				}
			}
			sysUser.setSiteName(siteName);
		}
		this.renderJson(JqGridModelUtils.toJqGridView(pageInfo));
	}

	/**
	 * 获取改组下所有用户
	 */
	@RequiresPermissions(value = { "/sys/user" })
	public void getUsertData()
	{
		String id = this.getPara("id");
		String select = "select su.*, (select group_concat(name) as roleNames from sys_role where id in(select role_id from sys_user_role where user_id=su.id)) as roleNames";
		StringBuffer sqlExceptSelect = new StringBuffer("from sys_user su where id = " + id);

		Page<SysUser> pageInfo = SysUser.me.getPage(this.getPage(), this.getRows(), select, sqlExceptSelect.toString(),
				this.getOrderby());
		this.renderJson(SysUser.me.toJqGridView(pageInfo));
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void delete()
	{
		String ids = this.getPara("ids");
		InvokeResult result = SysUser.me.setVisible(ids);
		this.renderJson(result);
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void objInfo()
	{
		Integer id = this.getParaToInt("id");
		this.setAttr("id", id);
		render("obj_info.jsp");
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void add()
	{
		Integer id = this.getParaToInt("id");
		if (id != null)
		{
			this.setAttr("item", SysUser.me.findById(id));
		}
		List<SysRole> list = SysRole.me.getSysRoleNamelist();
		this.setAttr("roleList", list);
		this.setAttr("id", id);
		render("user_add.jsp");
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void setParams()
	{
		String uids = this.getPara("uids");
		SysUser user = SysUser.me.findById(uids);
		this.setAttr("uids", uids);
		this.setAttr("params", user.getParams());
		render("params_add.jsp");
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void paramsSave()
	{
		String uids = this.getPara("uids");
		String param = this.getPara("param");
		this.renderJson(SysUser.me.saveParams(uids, param));
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void save()
	{
		String username = this.getPara("name");
		String password = this.getPara("password");
		String chinese = this.getPara("chinese");
		Integer id = this.getParaToInt("id");
		String des = this.getPara("des");
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		List<SysUserRole> list = SysRole.me.getRole(getRequest());
		List<SysSite> SiteList = new ArrayList<SysSite>();
		// 如果是站点管理员，默认创建站点用户，角色为3
		if (SysRole.me.checkIsSiteAdmin(list))
		{
			SysUser.me.save(id, username, password, des, chinese, user.getId(), 3);
		}
		InvokeResult result = SysUser.me.save(id, username, password, des, chinese, user.getId(), null);
		this.renderJson(result);
	}

	@RequiresPermissions(value = { "/sys/user" })
	public void userRoleSetting()
	{
		Integer uid = this.getParaToInt("uid");
		this.setAttr("item", SysUser.me.findById(uid));
		InvokeResult result = SysRole.me.getRoleZtreeViewList(uid);
		this.setAttr("jsonTree", result);
		render("user_role_setting.jsp");
	}

	@RequiresPermissions(value = { "/sys/user" })
	@Before(Tx.class)
	public void saveUserRoles()
	{
		Integer uid = this.getParaToInt("id");
		String roleIds = this.getPara("roleIds");
		InvokeResult result = SysUser.me.changeUserRoles(uid, roleIds);
		this.renderJson(result);
	}

	// 二期

	/**
	 * 获取所有用户名和id
	 */
	@RequiresPermissions(value = { "/sys/user" })
	public void getAllUsertList()
	{
		List<Lable> result = new ArrayList<Lable>();
		StringBuilder sql = new StringBuilder();
		sql.append("select id ,name from sys_user");
		List<Record> list = Db.find(sql.toString());
		for (Record record : list)
		{
			Lable lable = new Lable();
			lable.setId(record.getInt("id"));
			lable.setText(record.getStr("name"));
			result.add(lable);
		}
		this.renderJson(InvokeResult.success(result));
	}

}
